<template>
  <a-tree-select
class="compare-tree-select" v-model:value="treeValue" style="width: 100%" :tree-data="formatTreeData"
    tree-checkable placeholder="选择" tree-node-filter-prop="label" :field-names="fieldNames" :maxTagCount="1"
    showCheckedStrategy="SHOW_PARENT" @select="handleCheck" :treeDefaultExpandedKeys="defaultExpandedKeys"
    popupClassName: popupClassName='form-search-tree-select' labelInValue />
</template>
<script setup
  lang="ts">
  import { DataNode } from 'ant-design-vue/lib/tree'
  import { last, cloneDeep } from 'lodash-es'
  import { onMounted, watch, ref } from 'vue'

  defineOptions({ name: 'TreeSelect' })
  const emit = defineEmits(['changeValue'])

  const props = defineProps({
    treeData: {
      type: Array,
      default: () => []
    },
    disabledKey: {
      type: String,
      default: undefined
    },
    // 获取第几个可选设备
    index: {
      type: Number,
      default: undefined
    }
  })
  const treeValue = ref()
  const formatTreeData = ref()
  const defaultExpandedKeys = ref<string[]>([])
  const fieldNames = { value: 'treeId', label: 'classifyName', children: 'children' }

  onMounted(() => {
    if (props.treeData.length) {
      setTreeData()
    }
  })
  watch(
    () => props.treeData,
    (newVal) => {
      setTreeData()
    }
  )
  const setTreeData = () => {
    formatTreeData.value = cloneDeep(props.treeData)
    const { expandKeys, nodeData } = findNthCheckableAndExpandKeys()
    defaultExpandedKeys.value = expandKeys
    const checkedValue = expandKeys.length ? [last(expandKeys)] : []
    handleCheck(checkedValue, nodeData)
  }

  watch(
    () => props.disabledKey,
    (newVal) => {
      formatTreeData.value = disableNodeById(props.treeData, newVal)
    }
  )
  // 两个设备选框，不能选择相同 id
  const disableNodeById = (treeData, disabledKey) => {
    const traverse = (nodes: DataNode[]): DataNode[] => {
      return nodes.map(node => {
        if (node[fieldNames.value] === disabledKey) {
          return { ...node, disableCheckbox: true }
        }
        if (node.children) {
          return { ...node, children: traverse(node.children) }
        }
        return node
      })
    }

    return traverse(treeData)
  }

  const findNthCheckableAndExpandKeys = () => {
    const { treeData, index } = props
    const expandKeys: any[] = []
    let nodeData = {}
    let currentCount = 0

    const traverse = (node: DataNode, parentIds: any[] = []): boolean => {
      if (node.disableCheckbox) {
        return false
      }

      if (node.checkable) {
        currentCount += 1
        if (currentCount === index) {
          expandKeys.push(...parentIds, node[fieldNames.value])
          nodeData = node
          return true
        }
      }

      if (node.children) {
        for (let child of node.children) {
          if (traverse(child, [...parentIds, node[fieldNames.value]])) {
            return true
          }
        }
      }

      return false
    }

    for (let rootNode of treeData as DataNode[]) {
      if (traverse(rootNode)) break
    }

    return { expandKeys, nodeData }
  }

  const handleCheck = (value, nodeData) => {
    treeValue.value = value
    emit('changeValue', { value, nodeData })
  }


</script>
<style scoped
  lang="scss">
  .compare-tree-select {
    :deep(.ant-select-selection-item) {
      border: none;
      background: transparent;
    }

    :deep(.ant-select-selection-item-remove) {
      display: none;
    }

    :deep(.ant-select-selector) {
     height: 32px;
    }
  }
</style>
